package com.atgm.mall.gmmailproduct.service.impl;

import com.atgm.common.constant.RedisConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.GameException;
import com.atgm.mall.gmmailproduct.dao.GameTypeDao;
import com.atgm.mall.gmmailproduct.entity.GameTypeEntity;
import com.atgm.mall.gmmailproduct.service.GameTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.cache.annotation.CacheRemove;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class GameTypeServiceImpl extends ServiceImpl<GameTypeDao, GameTypeEntity> implements GameTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    @Cacheable(cacheNames = "game-type", key = "#root.targetClass")
    public List<GameTypeEntity> queryList() {
        List<GameTypeEntity> list = null;
        /**
         * 分布式锁：解决redis中缓存击穿
         */
        RLock lock = redissonClient.getLock(RedisConstant.Lock.GAME_TYPE_LOCK);
        //阻塞式等待； 具有看门狗，锁的自动续期，解决业务超长而释放锁的问题，默认加锁时间30秒
//        lock.lock(10, TimeUnit.SECONDS);  不具备看门狗性质
        lock.lock(10, TimeUnit.SECONDS);
        try {
            list  = baseMapper.selectList(null);
        } catch (Exception e) {
            return list;
        }finally {
            //释放锁
            lock.unlock();
        }
        //将结果放入redis
        return list;
    }

    @Override
    @CacheEvict(cacheNames = "game-type", key = "#root.targetClass")
    public void insertGameType(GameTypeEntity gameTypeEntity) {
        int count = baseMapper.insert(gameTypeEntity);
        if (count != 1) {
            throw new GameException("添加游戏类型失败", BizCodeEnume.GAME_TYPE.getCode());
        }
    }

    @Override
    @CacheEvict(cacheNames = "game-type", key = "#root.targetClass")
    public void removeGameTypeById(Long id) {
        int count = baseMapper.deleteById(id);
        if (count != 1) {
            throw new GameException("删除游戏类型失败", BizCodeEnume.GAME_TYPE.getCode());
        }
    }

    @Override
    @CacheEvict(cacheNames = "game-type", key = "#root.targetClass")
    public GameTypeEntity updateGameType(GameTypeEntity gameTypeEntity) {
        int count = baseMapper.updateById(gameTypeEntity);
        if (count != 1) {
            throw new GameException("修改游戏类型失败", BizCodeEnume.GAME_TYPE.getCode());
        }
        return gameTypeEntity;
    }
}
